package org.whuims.core.dataprocessor.page;

import org.apache.commons.lang3.StringUtils;
import org.whuims.core.utils.Mysql;

import java.io.File;
import java.sql.*;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by cheng on 2016/12/29.
 */
public class DocListProcessor {
    Map<Long, String> idPathMap = new TreeMap<Long, String>();
    Map<Long, String> idTextMap = new TreeMap<Long, String>();
    Map<Long, String> idQuotasMap = new TreeMap<Long, String>();

    public static void main(String[] args) {
        DocListProcessor processor = new DocListProcessor();
        try {
            processor.process();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void process() throws SQLException {
        loadInitialMap();
    }

    private void loadInitialMap() throws SQLException {
        Connection conn = Mysql.getConn("stdmem");
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("select id,cat_std,txt_path from std_std where valid=1");
        while (rs.next()) {
            Long id = rs.getLong("id");
            String catStd = rs.getString("cat_std");
            String txtName = rs.getString("txt_path");
            if (catStd == null || txtName == null) continue;
            String filePath = "src/main/webapp/resource/txt/" + catStd.trim() + "/" + txtName.trim();
            idPathMap.put(id, filePath);
        }
        rs.close();
        stmt.close();
        for (Map.Entry<Long, String> entry : idPathMap.entrySet()) {
            Long id = entry.getKey();
            String filePath = entry.getValue();
            File file = new File(filePath);
            System.out.println(file.getAbsolutePath());
            SentStructureBuilder builder = new SentStructureBuilder(filePath);
            String text = builder.build();
            this.idQuotasMap.put(id, StringUtils.join(builder.getQuotas(), " "));
            this.idTextMap.put(id, text);
        }
        for (Map.Entry<Long, String> entry : idTextMap.entrySet()) {
            PreparedStatement pstmt = conn.prepareStatement("update std_std set text_ocr=? where id=?");
            pstmt.setString(1, entry.getValue());
            pstmt.setLong(2, entry.getKey());
            pstmt.execute();
            pstmt.close();
        }
        for (Map.Entry<Long, String> entry : idQuotasMap.entrySet()) {
            PreparedStatement pstmt = conn.prepareStatement("update std_std set quotas=? where id=?");
            pstmt.setString(1, entry.getValue());
            pstmt.setLong(2, entry.getKey());
            pstmt.execute();
            pstmt.close();
        }
        conn.close();
    }
}
